#define _CRT_SECURE_NO_WARNINGS
#include "HardwareSerial.h"
#include "SerialPort.h"
#include <stdio.h>



#define KEY_DOWN(VK_NONAME) ((GetAsyncKeyState(VK_NONAME) & 0x8000) ? 1:0)

CSerialPort * cSerialPort;

HardwareSerial Serial;

void pinMode(uint8_t pin, uint8_t mode){

}

int digitalRead(uint8_t pin){
    if(pin==0){
        if (KEY_DOWN(VK_LBUTTON)) {
            return 0;
        }
        return 1;
    }
    if(pin==1){
        if (KEY_DOWN(VK_MBUTTON)) {
            return 1;
        }
        return 0;
    }
    if(pin==2){
        if (KEY_DOWN(VK_RBUTTON)) {
            return 0;
        }
        return 1;
    }
    return 1;
}



void digitalWrite(uint8_t pin, uint8_t val){
    cSerialPort->SetRts(!val);
}

HardwareSerial::HardwareSerial(){
    cSerialPort=new CSerialPort();
    cSerialPort->Open(CON_COM_PORT);
}

void HardwareSerial::begin(unsigned long baud){

};

size_t HardwareSerial::write(uint8_t v){
    uint8_t buf[1];
    buf[0] = v;
    cSerialPort->Send(buf,1);
    return 0;
}


size_t HardwareSerial::write(const uint8_t *buffer, size_t size){

    cSerialPort->Send((BYTE*)buffer, size);
    return size;
}

size_t HardwareSerial::readBytes(uint8_t *buffer, size_t length){
    DWORD r= cSerialPort->Receive(buffer, length);
    return r;
}

size_t HardwareSerial::readBytes(char* buffer, size_t length) {
    DWORD r = cSerialPort->Receive((uint8_t*)buffer, length);
    return r;
}


size_t HardwareSerial::printf(const char * format, ...){
    char log_buf[256];
    va_list args;

    /* args point to the first variable parameter */
    va_start(args, format);
    /* You can add your code under here. */
    sprintf(log_buf, format, args);
    uint32_t len= strnlen(log_buf,256);
    cSerialPort->Send((BYTE *)log_buf, len);
    va_end(args);
    return 0;

}

int HardwareSerial::available(void) {
    uint32_t r= cSerialPort->GetBytesInCOM();
    return r;
}